package com.rub.prajna.core

import javafx.animation.Interpolator
import javafx.animation.Transition
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.util.Duration
import kotlin.math.floor

/**
 * https://stackoverflow.com/questions/28183667/how-i-can-stop-an-animated-gif-in-javafx
 */
open class Animation : Transition {

    var imageView: ImageView? = null
    private var count = 0
    private var lastIndex = 0

    private lateinit var sequence: ArrayList<Image?>

    constructor() {}


    fun init(sequence: ArrayList<Image?>, durationMs: Double, imageView: ImageView) {
        this.imageView = imageView
        this.sequence = sequence
        count = sequence.size
        cycleCount = 1
        cycleDuration = Duration.millis(durationMs)
        interpolator = Interpolator.LINEAR
    }

    override fun interpolate(k: Double) {
        val index = floor(k * count).toInt().coerceAtMost(count - 1)
        //  println("index=$index")
        if (index != lastIndex) {
            imageView!!.image = sequence[index]
            lastIndex = index
        }
    }
}